<?php

namespace Admin\Model;

use Think\Model;

class ApiModel extends Model {

    //字段映射
    protected $_map = array(
        'api_code'       => 'code',
        'api_name'       => 'name',
        'api_module'     => 'module',
        'api_controller' => 'controller',
        'api_action'     => 'action',
        'api_param'      => 'params',
        'api_desc'       => 'description',
        'api_example'    => 'example',
        'api_method'     => 'method',
        'api_param1'     => 'params_json'
    );
    //自动验证
    protected $_validate = array(
        array('id','/^[1-9]\d*$/','请输入正确的API ID',1,'regex',2),
        array('code','/^_\w{1,}$/','请输入正确的API Code',1),
        array('code','','API Code已存在',1,'unique'),
        array('name','/^[\w\x{4e00}-\x{9fa5}]{2,}$/u','请输入正确的API Name',1),
        array('module','/^\w{2,}$/','请输入正确的API Module',1),
        array('controller','/^\w{2,}$/','请输入正确的API Controller',1),
        array('action','/^\w{2,}$/','请输入正确的API Action',1),
        array('method','1,2,3','请输入正确的API Method',1,'in'),
        //array('params', '/^\\{[\s\S]*\\}$/', '请输入正确的API Params', 1),
        array('params','require','请输入正确的API Params',1),
        //array('params_json', '/^\{(([\'\"])[\w\x{4e00}-\x{9fa5}]+\2:\2[\w\x{4e00}-\x{9fa5}]+\2),?)*\}$/', '请输入JSON格式的API Params', 1),
        array('description','/^[\s\S]*$/','请输入正确的API Description',1),
        //array('example', '/^\\{[\s\S]*\\}$/', '请输入正确的API Example', 1),
        array('example','require','请输入正确的API Example',1),
    );
    //自动完成
    protected $_auto = array(
        array('status','1'),
        array('create_time','time',1,'function'),
        array('update_time','time',3,'function'),
    );

    /**
     * 添加API
     * @author 刘新
     */
    public function addApi() {
        //创建为数据对象
        $res    = $this->create();
        if(!$res)
            return array('error' => 1,'msg' => $this->getError());
        $return = array('error' => 0,'msg' => '添加API成功');
        $res    = $this->add();

        if(!$res) {
            //添加失败，写入错误日志
            \Think\Log::record($e->getMessage(),'WARN',true);
            $return = array('error' => 1,'msg' => '添加API失败，请查看错误日志');
        }

        return $return;
    }

    /**
     * 编辑API
     * @author 刘新
     */
    public function editApi() {
        //创建为数据对象
        $res    = $this->create();
        if(!$res)
            return array('error' => 1,'msg' => $this->getError());
        $return = array('error' => 0,'msg' => '添加API成功');
        $res    = $this->save();

        if(!$res) {
            //编辑失败，写入错误日志
            \Think\Log::record($e->getMessage(),'WARN',true);
            $return = array('error' => 1,'msg' => '编辑API失败，请查看错误日志');
        }

        return array('error' => 0,'msg' => '编辑成功');
    }

}
